<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;


use App\Models\Admin\OfflineMerchantBanner;

class BannerController extends CommonController{

	protected $model;

	public function __construct()
	{
		parent::__construct();
		$this->model = new OfflineMerchantBanner;
	}

	public function index()
	{
		$data = $this->model->where(array('merchant_id' => $this->merchant_id))->orderBy('rank', 'asc')->paginate(10);
		return view('admin.banner.index')->with(['data' => $data]);
	}

	/**
	 * banner图添加/修改
	 */
	public function add(Request $request)
	{
		if($request->isMethod('post')) {

			$img_url = $request->input('img_url', '');
			$title = $request->input('title');
			$link_url = $request->input('link_url');
			if(!$img_url) $this->ajax_error('请上传图片');
			if(!$title) $this->ajax_error('请填写标题');

			$id = $request->input('id', 0);

			$data = array(
				'img_url'		=> $img_url,
				'title'		=> $title,
				'link_url'		=> $link_url,
				'rank'			=> (int)$request->input('rank', 0),
			);

			if($id)
			{
				if(!$this->model->where(array('merchant_id' => $this->merchant_id, 'id' => $id))->update($data)) $this->ajax_error('连接失败，请重新提交');
			}else
			{	
				$data['id'] = $this->model->getNextSeq();
				$data['merchant_id'] = $this->merchant_id;
				$data['add_time'] = date('Y-m-d H:i:s');
				if(!$this->model->insert($data)) $this->ajax_error('连接失败，请重新提交');
			}

			$this->ajax_success('提交成功');
			
		}else{
			$id = (int)$request->input('id', 0);

			if($id){
				$data = $this->model->where(array('merchant_id' => $this->merchant_id, 'id' => $id))->first();
			}else{
				$data = array();
			}
			
			return view('admin.banner.add')->with(['data' => $data]);
		}

	}

	/**
	 * 删除banner
	 */
	public function del(Request $request)
	{
		$id = $request->input('id', 0);
		if(!$id) $this->ajax_error('操作失败');

		if(!$this->model->where(array('merchant_id' => $this->merchant_id, 'id' => $id))->delete()) $this->ajax_error('操作失败，请重试');
		$this->success('删除成功');		
	}


}